package com.woniu.cq.mallgateway.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Daniel
 * @version 1.0.0
 * @ClassName GlobalExceptionHandler
 * @Description 全局异常
 * @createTime 2020年09月24日 18:54:00
 */
@Component
@Order(-1)
public class GlobalExceptionHandler implements ErrorWebExceptionHandler {
    ObjectMapper objectMapper = new ObjectMapper();
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        Map<String, Object> error = new HashMap<>();
        error.put("code",500);
        error.put("msg",ex.getMessage());
        error.put("error",ex);
        exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);
        return exchange.getResponse().writeWith(Mono.fromSupplier(()->{
            try {
                return exchange.getResponse().bufferFactory().wrap(objectMapper.writeValueAsBytes(error));
            }catch (Exception e){
                e.printStackTrace();
                return null;
            }
        }));
    }
}
